package com.example.exam.tools;

import com.example.exam.pojo.Enum.SystemCode;
import com.example.exam.pojo.Exception.ServiceException;
import lombok.Data;

import java.io.Serializable;

/**
 * 统一的响应结果类型
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Data
public class JsonResult<T> implements Serializable {

    /**
     * 业务状态码
     */
    private Integer code;
    /**
     * 消息
     */
    private String message;
    /**
     * 数据
     */
    private T response;


    public JsonResult(int code, String message){
        this.code=code;
        this.message=message;
    }
    public JsonResult(int code, String message, T response){
        this.code=code;
        this.message=message;
        this.response=response;
    }
    public JsonResult() {

    }

    public static JsonResult ok() {
        return ok(null);
    }

    public static <T> JsonResult<T> ok(T response) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(SystemCode.OK.getCode());
        jsonResult.setMessage(SystemCode.OK.getMessage());
        jsonResult.setResponse(response);
        return jsonResult;
    }

    public static JsonResult<Void> fail(ServiceException e) {
        return fail(e.getState(), e.getMessage());
    }

    public static JsonResult<Void> fail(Integer state, String message) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(state);
        jsonResult.setMessage(message);
        return jsonResult;
    }

}
